import React, {Component} from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  Dimensions,
  TouchableWithoutFeedback,
  TouchableOpacity,
  Button,
} from 'react-native';
import {Tao_haoDao_Ratesurl, trill_data} from '../../api/haoDan';
import Video from 'react-native-video';
import Swiper from 'react-native-swiper';
const {width, height} = Dimensions.get('window');
import MarqueeLabel from 'react-native-lahk-marquee-label';
import {JumpTo} from '../../utils/Taobao';
import EventBus from '../../utils/EventBus';
import {EasyLoading, Loading} from '../../components/EasyLoading';
const default_state = {
  list: [],
  cid: 0,
  list_page: 1,
  list_loading: false,
  list_error: false,
  list_end: false,
  paused: true,
  resizeMode: 'cover',
};

export default class Douhuo extends Component {
  // static navigationOptions = {
  //   title: '抖货',

  //   tabBarOnPress: (event) => {
  //     //调用组建内默认的实现方法
  //     event.defaultHandler();
  //     console.log('回到抖货');
  //     this.RfVideoData();
  //   },
  // };

  static navigationOptions = ({navigation, navigationOptions, screenProps}) => {
    // const {params} = navigation.state;
    return {
      tabBarVisible: true,
      title: '抖货',
      tabBarOnPress: (event) => {
        //调用组建内默认的实现方法
        event.defaultHandler();
        EventBus.emit('RefVideo');
      },
    };
  };

  constructor(props) {
    super(props);

    this.state = {
      list: [],
      video: [],
      videoWidth: width,
      videoHeight: height,
      swiperIndex: 0,
      curDataIndex: 0,
      paused: false,
    };
  }

  // 点击完成按钮
  order = () => {
    console.log('order');
  };

  componentDidMount() {
    // this.props.navigation.setParams({navigatePress: this.order});
    this.GetData();
    this.subscribe = EventBus.addListener('douying', (data) => {
      var video1 = this.state.list;
      video1[0].muted = true;
      video1[1].muted = true;
      video1[2].muted = true;
      this.setState({
        video: video1,
      });
    });

    this.subscribe2 = EventBus.addListener('RefVideo', (data) => {
      console.log('Event ref');
      this.RfVideoData();
    });
  }
  componentWillUnmount() {
    EventBus.remove(this.subscribe);
    EventBus.remove(this.subscribe2);
  }

  /**
   * 获取数据
   */
  GetData() {
    const {cid, list, list_loading, list_end, list_page} = this.state;
    if (list_loading && list_end) {
      return;
    }
    this.setState(
      {
        list_loading: true,
        list_error: false,
        list_end: false,
      },
      () => {
        trill_data(list_page, cid).then((res) => {
          if (res === null) {
            // eslint-disable-next-line no-undef
            Toast.offline('网络错误~', 3, undefined, false);
            this.setState(
              {
                list_loading: false,
                curDataIndex: 0,
              },
              () => {
                this.RfVideoData();
              },
            );
          } else {
            this.setState(
              {
                list_loading: false,
                list: list.concat(res.data),
                list_page: res.min_id,
              },
              () => {
                // console.log('重新获取数据后：' + this.state.list.length);
                this.RfVideoData();
              },
            );
            this.rc && this.rc.finishRefresh();
          }
        });
      },
    );
  }

  getVideoList(num1, num2, num3) {
    var video = this.state.list;

    if (num1 < 0) {
      num1 = this.state.list.length + num1;
    }
    if (num2 < 0) {
      num2 = this.state.list.length + num2;
    }
    if (num3 < 0) {
      num3 = this.state.list.length + num3;
    }

    var item = [video[num1], video[num2], video[num3]];
    return item;
  }

  RfVideoData() {
    if (this.state.list_loading === true) {
      return;
    }
    var swiperIndex = this.state.swiperIndex;
    var curDataIndex = this.state.curDataIndex;

    var item = [];
    if (swiperIndex === 0) {
      item = this.getVideoList(
        curDataIndex,
        curDataIndex + 1,
        curDataIndex - 1,
      );
      item[0].muted = false;
      item[1].muted = true;
      item[2].muted = true;
      if (this.player1 !== null && this.player1 !== undefined) {
        this.player1.seek(0);
      }
    }
    if (swiperIndex === 1) {
      item = this.getVideoList(
        curDataIndex - 1,
        curDataIndex,
        curDataIndex + 1,
      );
      item[0].muted = true;
      item[1].muted = false;
      item[2].muted = true;
      if (this.player2 !== null && this.player2 !== undefined) {
        this.player2.seek(0);
      }
    }
    if (swiperIndex === 2) {
      item = this.getVideoList(
        curDataIndex + 1,
        curDataIndex - 1,
        curDataIndex,
      );
      item[0].muted = true;
      item[1].muted = true;
      item[2].muted = false;
      if (this.player3 !== null && this.player3 !== undefined) {
        this.player3.seek(0);
      }
    }
    this.setState({
      video: item,
      paused: false,
    });
  }

  onChangeValue = (index) => {
    // console.log('onChangeValue');
    var last_curIndex = this.state.curDataIndex;
    var cur = index - this.state.swiperIndex;
    if (cur === 1 || cur === -2) {
      // console.log('上滑');
      last_curIndex = last_curIndex + 1;
    } else if (cur === -1 || cur === 2) {
      // console.log('下滑');
      last_curIndex = last_curIndex - 1;
    }
    this.setState(
      {
        swiperIndex: index,
        curDataIndex: last_curIndex,
      },
      () => {
        if (last_curIndex + 1 >= this.state.list.length) {
          console.log('重新获取数据');
          this.GetData();
        } else {
          this.RfVideoData();
        }
      },
    );
  };

  createSwiperItem(item, name) {
    if (item === null || item === undefined) {
      return <View />;
    }

    return (
      <View style={styles.container}>
        <View
          style={{
            position: 'absolute',
            left: 0,
            top: 0,
            width: this.state.videoWidth,
            height: this.state.videoHeight,
            backgroundColor: '#000000',
          }}>
          {item === undefined ? (
            <View />
          ) : (
            <TouchableWithoutFeedback
              onPress={() => {
                var temp = this.state.paused === true ? false : true;
                this.setState({
                  paused: temp,
                });
              }}>
              <Video
                ref={(ref) => {
                  if (name === '1') {
                    this.player1 = ref;
                  }
                  if (name === '2') {
                    this.player2 = ref;
                  }
                  if (name === '3') {
                    this.player3 = ref;
                  }
                }}
                source={{uri: item.dy_video_url}}
                paused={this.state.paused}
                muted={item.muted}
                resizeMode={'contain'}
                playWhenInactive={false}
                playInBackground={false}
                onLoad={() => {}} //加载媒体并准备播放时调用的回调函数。
                ignoreSilentSwitch={'ignore'}
                progressUpdateInterval={250.0}
                repeat={true}
                style={{
                  width: this.state.videoWidth,
                  height: this.state.videoHeight,
                }}
              />
            </TouchableWithoutFeedback>
          )}

          <View style={styles.viewParent}>
            <View style={styles.view}>
              <Text style={styles.shop}>@{item.shopname}</Text>
              <Text numberOfLines={3} style={styles.des}>
                {item.recommendation}
              </Text>
              <View style={styles.juanContain}>
                <Text style={styles.juanhou}>
                  卷后价￥
                  <Text style={styles.price}>
                    {item.quanhouPrice}
                    <Text style={styles.truePrice}>￥{item.realPrice}</Text>
                  </Text>
                </Text>
              </View>
            </View>
          </View>
        </View>
        <View style={styles.btn}>
          <TouchableOpacity
            style={styles.btn_1}
            onPress={() => {
              EasyLoading.show();
              Tao_haoDao_Ratesurl(item.productId, item.title).then((res) => {
                EasyLoading.dismiss();
                JumpTo(res);
              });
            }}>
            <Text style={styles.text_1}>购</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.AtNoticebar}>
          <MarqueeLabel
            // style={styles.AtNoticebar}
            duration={15 * 1000}
            // eslint-disable-next-line react-native/no-inline-styles
            textStyle={{fontSize: 13, color: 'white'}}>
            {/* @{item.dy_video_title},{item.itemdesc} */}
            @小陶,欢迎您的购买！
          </MarqueeLabel>
        </View>
        <Loading />
      </View>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <Swiper
          showsButtons={false}
          horizontal={false}
          autoplay={false} //自动轮播
          showsPagination={false}
          onIndexChanged={(index) => {
            this.onChangeValue(index);
          }}>
          {this.createSwiperItem(this.state.video[0], 'player1')}
          {this.createSwiperItem(this.state.video[1], 'player2')}
          {this.createSwiperItem(this.state.video[2], 'player3')}
        </Swiper>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  fullScreen: {
    flex: 1,
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'red',
  },
  video: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'yellow',
    width: 100,
    height: 100,
  },
  slide: {
    flex: 1,
    backgroundColor: 'transparent',
  },
  imgBackground: {
    width,
    height,
    backgroundColor: 'transparent',
    position: 'absolute',
  },

  image: {
    width,
    height,
  },

  viewParent: {
    position: 'absolute',
    flex: 1,
    alignItems: 'center',
    flexDirection: 'row',
    bottom: 45,
    backgroundColor: 'rgba(0, 0, 0, 0.2)',
    height: 150,
    width: '100%',
  },

  view: {
    flex: 1,
    position: 'relative',
    flexDirection: 'column',
    //background: #f33a57;
    height: 140,
    width: '75%',
    marginLeft: 20,
  },

  shop: {
    //background: rgba(214, 214, 214, 0.33);
    color: '#f3f3f4',
    fontSize: 18,
    fontWeight: 'bold',
  },

  des: {
    //background: rgba(214, 214, 214, 0.33);
    color: 'rgba(255, 255, 255, 0.8)', //'#f3f3f4',
    fontSize: 14,
    fontWeight: 'bold',
    // display: '-webkit-box',
    overflow: 'hidden',
    // '-webkit-line-clamp': 3,
    // '-webkit-box-orient': 'vertical',
    // textOverflow: 'ellipsis',
    width: '80%',
    // backgroundColor: 'rgba(0, 0, 0, 0.2)',
    // wordBreak: 'break-word',
  },
  priceParent: {
    // flex: 1,
    flexDirection: 'row',
  },
  AtNoticebar: {
    position: 'absolute',
    // top: 199,
    // left: 0,
    // right: 0,
    bottom: 0,
    backgroundColor: 'rgba(253, 253, 253, 0)',
    width: 100,
    height: 50,
    color: 'rgba(243, 243, 244, 0.8)',
    fontWeight: 'bold',
  },
  juanContain: {
    flex: 1,
    // justifyContent: 'space-between',
    flexDirection: 'row',
  },
  juanhou: {
    fontSize: 15,
    color: '#e23c03',
    fontWeight: 'bold',
  },
  price: {
    fontSize: 20,
    color: '#e20009',
    fontWeight: 'bold',
  },
  truePrice: {
    color: '#ffffff',
    marginLeft: 5,
    // text-decoration-line: line-through;
    textDecorationLine: 'line-through',
    fontSize: 15,
    fontWeight: 'bold',
  },
  btn: {
    position: 'absolute',
    bottom: 30,
    right: 10,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 192, 203, 0.8)',
    width: 50,
    height: 50,
    zIndex: 100,
    borderRadius: 20,
  },
  btn_1: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    width: '100%',
    height: '100%',
  },
  text_1: {
    fontSize: 25,
    color: 'white',
  },
});
